package com.igeek.compus.test.product.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.igeek.compus.test.menu.entity.Menu;
import com.igeek.compus.test.product.entity.Product;
import com.igeek.compus.test.product.service.ProductService;
import com.igeek.compus.test.system.Constants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("product")
@Controller
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 展示商品列表，分页
     * @param product
     * @return
     */
    @RequestMapping("list.do")
    @ResponseBody
    public Map<String, Object> list(Product product) {
        Map<String, Object> result = new HashMap<>();

        try {

            PageInfo<Product> productPageInfo = new PageInfo<>(productService.getProductListByPage(product));            int count = productService.getProductListCount(product);

            result.put(Constants.RETDATA, productPageInfo.getList());
            result.put(Constants.COUNT, productPageInfo.getTotal());

            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
        } catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.ERROR_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        return result;
    }

    @RequestMapping("deleteProductById.do")
    @ResponseBody
    public void deleteProductById(Product product) {
        System.out.println(product);
        productService.deleteProductById(product);
    }

    @RequestMapping("deleteProductList.do")
    @ResponseBody
    public Map<String, Object> deleteProductList(String productIds) {
        Map<String, Object> result = new HashMap<>();

        List<String> productIdList = Arrays.asList(productIds.substring(1, productIds.length() - 1).split(","));

        // 2.执行业务
        try {
            if (productService.deleteProductList(productIdList) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            } else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    @RequestMapping("addProduct.do")
    @ResponseBody
    public Map<String, Object> addProduct(Product product) {
        Map<String, Object> result = new HashMap<>();

        // 1.参数校验
        if(StrUtil.isEmpty(product.getProductName()) || StrUtil.isEmpty(product.getNickName())
                || product.getPrice() == null) {
            result.put(Constants.RETCODE, Constants.ERROR_CODE);
            result.put(Constants.RETMSG, Constants.PARAM_ERROR_MSG);
            return  result;
        }

        // 2.执行业务
        try {
            if(productService.addProduct(product) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    @RequestMapping("toProductEdit.do")
    public ModelAndView toProductEdit(Integer id) {
        // 通过id查询menu信息
        Product product = productService.getProductInfoById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("id", product.getId());
        map.put("nickName", product.getNickName());
        map.put("productName", product.getProductName());
        map.put("description", product.getDescription());
        map.put("price", product.getPrice());
        map.put("create_time", product.getCreateTime());

        return new ModelAndView("/product/product_edit", map);
    }

    @RequestMapping("updateProduct.do")
    @ResponseBody
    public Map<String, Object> updateProduct(Product product) {
        Map<String, Object> result = new HashMap<>();

        // 1.参数校验
        if(product.getId() == null) {
            result.put(Constants.RETCODE, Constants.ERROR_CODE);
            result.put(Constants.RETMSG, Constants.PARAM_ERROR_MSG);
            return  result;
        }

        // 2.执行业务
        try {
            if(productService.updateProduct(product) > 0) {
                result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }else {
                result.put(Constants.RETCODE, Constants.ERROR_CODE);
                result.put(Constants.RETMSG, Constants.SUCCESS_MSG);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
            result.put(Constants.RETMSG, Constants.ERROR_MSG);
        }

        // 3.返回结果
        return result;
    }

    @RequestMapping("exportProductList.do")
    public void export(Product product, HttpServletRequest request, HttpServletResponse response) throws Exception {

        OutputStream outputStream = null;

        try {

            // 1.查询菜单列表
            List<Product> productList = productService.getProductListByPage(product);

            String fileName = "商品报表.xls";
            String userAgent = request.getHeader("USER-AGENT").toLowerCase();
            String outputFileName = fileName;
            if (userAgent.toUpperCase().indexOf("MSIE") > 0) {
                outputFileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (userAgent.toUpperCase().indexOf("IPHONE") > 0) {
                outputFileName = new String(fileName.getBytes(), "ISO-8859-1");
            } else {
                outputFileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            }
            String[] titles = {"卖家名称", "商品名称", "商品描述", "商品价格", "发布时间"};

            // 2.导出excel，需要标题栏，需要数据
            HSSFWorkbook wb = productService.productExport(titles, productList);

            response.setContentType("application/octet-stream");
            // 以附件的形式下载
            response.setHeader("Content-disposition", "attachment; filename=\"" + outputFileName + "\"");

            outputStream = response.getOutputStream();
            wb.write(outputStream);

            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
